<?php /** @noinspection ALL */

namespace app\api1\controller;

use chillerlan\QRCode\QRCode;
use hg\apidoc\annotation as Apidoc;

/**
 * 新订单
 *
 * api-NewOrders
 *
 * @Apidoc\Title("新订单")
 * @Apidoc\Group("api1")
 */
class NewOrders extends Auth
{
    /**
     * @Apidoc\Title("新增订单")
     */
    public function add()
    {
        $member_id = $this->request->uid;
        $product_id = input('product_id', 0, 'intval');
        $product = \app\common\model\RobotProducts::where('id', $product_id)->find();
        if (!$product) {
            return error('产品不存在');
        }
        if($product['price'] == 0){
            $free_robot = \app\common\model\Robot::where('robot_products_id', $product_id)
                ->where('member_id', $member_id)->find();
            if($free_robot){
                return error('您已经拥有机器人，无法创建免费机器人！');
            }
        }

        $order = [];
        $order['name'] = '购买机器人产品 ' . $product['name'];
        $order['member_id'] = $member_id;
        $order['product_type'] = 'robot';
        $order['purchase_type'] = 'new';
        $order['purchase_days'] = $product['duration_days'];
        $order['total_amount'] = $product['price'];
        $order['daily_price'] = number_format($product['price'] / $product['duration_days'], 2);
        $order['product_parameters'] = $product;
        $order['order_number'] = date('ymdHis',time()) . '_' . $member_id;

        $newOrder = \app\common\model\NewOrders::create($order);
        $newOrder->newOrderLog()->save(['name' => '创建订单']);

        // 如果价格为0，直接完成订单
        if($product['price'] == 0){
            PayCommon::completeRobotOrder($newOrder['id']);
        }
        return success('', ['order_id' => $newOrder['id']]);
    }


    /**
     * @Apidoc\Title("新增续费订单")
     */
    public function addRenew()
    {
        $member_id = $this->request->uid;
        $robot_id = input('robot_id', 0, 'intval');
        $robot = \app\common\model\Robot::find($robot_id);
        $product = \app\common\model\RobotProducts::find($robot['robot_products_id']);
        if (!$product) {
            return error('产品不存在');
        }


        $order = [];
        $order['name'] = '续费机器人产品 ' . $product['name'];
        $order['member_id'] = $member_id;
        $order['product_type'] = 'robot';
        $order['purchase_type'] = 'renew';
        $order['purchase_days'] = $product['duration_days'];
        $order['total_amount'] = $product['price'];
        $order['daily_price'] = number_format($product['price'] / $product['duration_days'], 2);
        $order['product_parameters'] = $product;
        $order['order_number'] = date('ymdHis',time()) . '_' . $member_id;
        $order['product_id'] = $robot_id;

        $newOrder = \app\common\model\NewOrders::create($order);
        $newOrder->newOrderLog()->save(['name' => '创建订单']);

        return success('', ['order_id' => $newOrder['id']]);
    }


    public function addUpgrade()
    {
        $product_id = input('product_id', 0, 'intval');
        $product = \app\common\model\RobotProducts::where('id', $product_id)->find();
        if (!$product) {
            return error('产品不存在');
        }
        $member_id = $this->request->uid;
        $robot_id = input('robot_id', 0, 'intval');
        $robot = \app\common\model\Robot::where('member_id', $member_id)->where('id', $robot_id)->find();
        if (!$robot) {
            return error('机器人不存在');
        }
        $now_product = \app\common\model\RobotProducts::where('id', $robot['robot_products_id'])->find();
        if($now_product['price'] >= $product['price']){
            return error('您的机器人已经比升级机器人更高级，无法再次升级！');
        }
        $diff_price = $product['price'] - $now_product['price'];
        $diff_per_day = ceil($diff_price / $product['duration_days']);
        $diff_days = ceil(($robot['expiration_time']  - time()) / 86400);
        $expire_time = $robot['expiration_time'];
        if($diff_days <= 0 || $now_product['price'] == 0){
            $diff_days = $product['duration_days'];
            $diff_money = $product['price'];
            $expire_time = time() + $diff_days * 86400;
        }else{
            $diff_money = $diff_days * $diff_per_day;
        }

        $product['from_product'] = $now_product;
        $product['diff_per_day'] = $diff_per_day;
        $product['diff_days'] = $diff_days;
        $product['expire_time'] = $expire_time;


        $order = [];
        $order['name'] = '升级机器人产品 ' . $product['name'];
        $order['member_id'] = $member_id;
        $order['product_type'] = 'robot';
        $order['purchase_type'] = 'upgrade';
        $order['purchase_days'] = $diff_days;
        $order['total_amount'] = $diff_money;
        $order['daily_price'] = number_format($product['price'] / $product['duration_days'], 2);
        $order['product_parameters'] = $product;
        $order['order_number'] = date('ymdHis',time()) . '_' . $member_id;
        $order['product_id'] = $robot_id;

        $newOrder = \app\common\model\NewOrders::create($order);
        $newOrder->newOrderLog()->save(['name' => '创建订单']);

        return success('', ['order_id' => $newOrder['id']]);
    }


    /**
     * @Apidoc\Title("获取订单支付二维码")
     */
    public function getQrCode()
    {
        $order_id = input('order_id', 0, 'intval');
        $order = \app\common\model\NewOrders::find($order_id);
        if (!$order) {
            return error('订单不存在');
        }
        $url = config('wechat.base_url') . '/api1/robotPay/pay?member_id=' . $this->request->uid . '&id=' . $order_id;
        $qrcode = (new QRCode)->render($url);
        return success('', ['qrcode' => $qrcode, 'order_num' => $order->order_number]);
    }


    /**
     * @Apidoc\Title("订单支付状态")
     */
    public function isOrderPayed()
    {
        $order_id = input('order_id', 0, 'intval');
        $order = \app\common\model\NewOrders::find($order_id);
        return success('', ['is_payed' => $order->is_payment]);
    }


    /**
     * @return \think\response\Json|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @Apidoc\Title("获取订单详情")
     * @Apidoc\Param("order_id", type="int", default="0", desc="订单ID")
     */
    public function getOrder()
    {
        $order_id = input('order_id', 0, 'intval');
        $order = \app\common\model\NewOrders::where('member_id',$this->request->uid)->where('id',$order_id)->find();
        if(!$order){
            return error('订单不存在');
        }
        $order = $order->toArray();
        if($order['purchase_type'] == 'renew'){
            $robot = \app\common\model\Robot::find($order['product_id']);
            $order['end_time'] = date('Y-m-d H:i:s',max(time(),$robot['expiration_time'] ) + $order['purchase_days'] * 24 * 3600);
        }
        if($order['purchase_type'] == 'upgrade'){
            $order['end_time'] = date('Y-m-d H:i:s', $order['product_parameters']['expire_time']);
        }
        return success('', $order);
    }

    /**
     * @Apidoc\Title("获取订单列表")
     */
    public function list()
    {
        $list_rows = input('list_rows', 10, 'intval');
        $data = \app\common\model\NewOrders::where('member_id', $this->request->uid)
            ->order('id', 'desc')
            ->paginate($list_rows);
        return success('', $data);
    }

    /**
     * @Apidoc\Title("获取订单列表")
     */
    public function getList()
    {
        $data = \app\common\model\NewOrders::where('member_id', $this->request->uid)
            ->where('is_payment',1)
            ->where('is_apply_for_invoice', 0)
            ->where('total_amount', '>' ,0)
            ->order('id', 'desc')
            ->select();
        return success('', $data);
    }










}